// pages/signin/signin.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: '',
    signInWay: 0,
    actSigns:[],
    index:null,
    status:null,
    textH:'',
    address:'' ,
    longitude:'' ,
    latitude: '',
    signRange: [],
    index:0,
    show:false,
    rice:500,
    value:[7]
  },
  bindChange: function (e) {
    const val = e.detail.value
    console.log('范围',e,val)
    this.setData({
      rice: this.data.signRange[val].dictValue,
    })
  },
  ricetrue() {
    let tem = 'actSigns[' + this.data.index + '].signRange'
    this.setData({
      [tem]: this.data.rice,
      show: false
    })
  },
  ricequ(){
    this.setData({
      show: false
    })
  },
  signinrice(e){
    this.setData({
      index: e.currentTarget.dataset.index,
      show:true,
      value:[7]
    })
  },
  signInWay0() {
    if (this.data.signInWay == 1) {
      this.setData({
        signInWay:0
      })
    }
  },
  signInWay1() {
    if (this.data.signInWay == 0) {
      this.setData({
        signInWay: 1
      })
    }
  },
  add(){
    var that= this
    var num = that.toChinesNum(that.data.actSigns.length+1)
    var arry = that.data.actSigns
    var arr={
      "startTime":"",
      "endTime":"",
      "latitude": that.data.latitude,
      "longitude":that.data.longitude,
      "address":that.data.address,
      'signRange':500,
      "scroll":num,
      "yearisClick": 'd' + (that.data.actSigns.length)
      }
      arry.push(arr)
      console.log('签到列表',arry)
    that.setData({
      actSigns: arry,
      yearisClick: 'd' + (that.data.actSigns.length-1)
    })
    // console.log('id名', that.data.yearisClick)
  },
  indexbtn(e){
    console.log('点击', e)
    this.setData({
      index: e.currentTarget.dataset.index
    })
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    console.log('picker发送选择改变，携带值为', e)
    let temp = 'actSigns[' + this.data.index + '].startTime'
    this.setData({
      [temp]: e.detail.value
    })
  },
  bindTimeChange1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    console.log('picker发送选择改变，携带值为', e)
    let end = 'actSigns[' + this.data.index + '].endTime'
    this.setData({
      [end]: e.detail.value
    })
  },
  openGPS(e) {
    var that = this;
    var index = e.currentTarget.dataset.index
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: function () {
              that.realOpenGPS(index);
            },
            fail: function (d) {
              wx.showModal({
                title: '获取授权失败',
                content: '是否前往设置允许小程序使用位置信息',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      complete: function (r) {
                        if (r.authSetting['scope.userLocation']) {
                          that.realOpenGPS(index);
                        }
                      }
                    });
                  }
                }
              })
            }
          })
        } else {
          that.realOpenGPS(index);
        }
      }
    });
  },
  //签到地点
  realOpenGPS(i) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.log('地点', res)
        let latitude = 'actSigns[' + i + '].latitude'
        let longitude = 'actSigns[' + i + '].longitude'
        let address = 'actSigns[' + i + '].address'
        that.setData({
          [latitude]: res.latitude,
          [longitude]: res.longitude,
          [address]: res.address
        })
        console.log('地点', that.data.actSigns)
      },
      fail(res) {
        console.log(res)
      }
    });
  },
  save(){
    var that = this
    var arr = that.data.actSigns
    if (that.data.signInWay==1){
    if (arr.length<=0){
      wx.showToast({
        title: '请添加签到信息',
        icon: 'none',
        duration: 2000
      })
      return;
    }else {
      //判断第几个元素是空的
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].startTime == "") {
          console.log([i] + "为空");
          wx.showToast({
            title: '签到' + [i+1] + '内有未填写内容，请完善后再保存',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (arr[i].endTime == "") {
          console.log([i] + "为空");
          wx.showToast({
            title: '签到' + [i+1] + '内有未填写内容，请完善后再保存',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (arr[i].address == "") {
          console.log([i] + "为空");
          wx.showToast({
            title: '签到' + [i+1] + '内有未填写内容，请完善后再保存',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (arr[i].signRange == "") {
          console.log([i] + "为空");
          wx.showToast({
            title: '签到' + [i + 1] + '内有未填写内容，请完善后再保存',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (arr[i].startTime > arr[i].endTime){
          wx.showToast({
            title: '签到' + [i+1] + '结束时间不能早于开始时间',
            icon: 'none',
            duration: 2000
          })
          return;
        }
      }
      let pages = getCurrentPages(),
        prevPage = pages[pages.length - 2];
      prevPage.setData({
        'act2.actSigns':arr,
        'act2.signInWay':1,
      })
      wx.navigateBack({})
    }
    } else if (that.data.signInWay==0){
      let pages = getCurrentPages(),
        prevPage = pages[pages.length - 2];
      prevPage.setData({
        'act2.signInWay': 0,
      })
      wx.navigateBack({})
    }
  },
del(e){
  var that = this
 var index = e.currentTarget.dataset.index
  console.log('删除', index)
  wx.showModal({
    content: '是否要将此项删除',
    cancelColor: '#999999',
    confirmColor: '#2168EB',
    success(res) {
      if (res.confirm) {
        that.remove(that.data.actSigns, index)
        that.sort()
      } else if (res.cancel) {
      }
    }
  })
  console.log('删除', that.data.actSigns)
},
sort(){
  var arr = this.data.actSigns
  for (let i = 0; i < arr.length; i++) {
    var num = this.toChinesNum(i+1)
    arr[i].scroll = num
  }
  this.setData({
    actSigns: arr,
    status: null
  })
  console.log(this.data.actSigns)
},
  //删除元素
  remove: function (array, val) {
    for (var i = 0; i < array.length; i++) {
      if (i == val) {
        array.splice(i, 1);
      }
    }
  },
  touchS(e) {
    // 获得起始坐标
    this.startX = e.touches[0].clientX;
    this.startY = e.touches[0].clientY;
  },
  touchM(e) {
    var index = e.currentTarget.dataset.index
    // 获得当前坐标
    this.currentX = e.touches[0].clientX;
    this.currentY = e.touches[0].clientY;
    const x = this.startX - this.currentX; //横向移动距离
    const y = Math.abs(this.startY - this.currentY); //纵向移动距离，若向左移动有点倾斜也可以接受
    if (x > 35 && y < 110) {
      //向左滑是显示删除
      this.setData({
        status: index
      })
    } else if (x < -35 && y < 110) {
      //向右滑
      this.setData({
        status: null
      })
    }
  },
    getkm(){
    var that = this
    app.req({
      url: "wechat/dictionary/listBydictType",
      method: "post",
      data: {
        dictType:'SIGN_RANGE'
      },
      success: function (res) {
        if (res.code == 200) {
          that.setData({
            signRange: res.data
          })
          console.log('字典项',res)
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    console.log(options)
    if (options.longitude != ''){
      that.setData({
        address: options.address,
        longitude: options.longitude,
        latitude: options.latitude,
      })
    }
    that.setData({
      actSigns: JSON.parse(decodeURIComponent(options.actSigns)),
    })
    if(that.data.actSigns.length>0){
      that.setData({
        signInWay: 1
      })
    }
    console.log('传递', that.data.actSigns)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    for (let i=0 ; i< that.data.actSigns.length;i++) {
      var num = that.toChinesNum(i+1)
      var scroll = "actSigns[" + i + "].scroll"
      that.setData({
        [scroll]: num,
      })
    }
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var textH = clientHeight * rpxR - 374;
        that.setData({
          textH: textH
        });
        console.log('祝福高度', that.data.textH)
      }
    });
    that.getkm()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 数字转换
  toChinesNum (num) {
        let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        let unit = ["", "十", "百", "千", "万"];
       num = parseInt(num);
       let getWan = (temp) => {
          　　let strArr = temp.toString().split("").reverse();
         　　let newNum = "";
       　　for (var i = 0; i < strArr.length; i++) {
            　　newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
      }
         　 return newNum;
    
    }
       let overWan = Math.floor(num / 10000);
       let noWan = num % 10000;
       if (noWan.toString().length < 4) {
      　　　　　　noWan = "0" + noWan;
    }
     return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
    
  }
})